function v = fill_date (u, mode)

   ## usage:  v = fill_date (u, mode)
   ##
   ## fill missing dates

   d = 1/10 ;

   if nargin < 2
      mode = "interpol" ;
   endif

   if !isstruct(u)
      v = u ;
      return
   endif

   if !isfield(u, "cal"), u.cal = "gregorian" ; endif

   if columns(u.id) > 3
      I = chkdst(u.id) ;
      u.id = u.id(I,:) ; u.x = u.x(I,:) ;
   endif

   nc = columns(u.id) ;
   while columns(u.id) < 3
      u.id = [u.id ones(rows(u.id), 1)] ;
   endwhile

   Ju = date2cal(u.id, u.cal) ;

   Judf = fixsort(Ju) ;
   Ju = Ju(Judf) ; u.id = u.id(Judf,:) ; u.x = u.x(Judf,:) ;

   I = fill_jul(Ju) ;

   v = u ;

   v.id = cell(1, nc) ;
   [v.id{:}] = cal2date(I, u.cal) ; v.id = cell2mat(v.id) ;

   if strcmp(mode, "interpol")
      v.x = interp1 (Ju, u.x, I) ;
      return ;
   endif

   j = 0 ; Lu = nan(rows(Ju),1) ;
   for i=1:rows(Ju)
      while j < length(I) && Ju(i) - I(++j) > d
	 ##disp([i j]) ;
      endwhile
      if j == length(I) && i < rows(Ju)
	 error("fill_date: running out of values for i = %d, at %d %d %d\n", i, u.id(i,1:3)) ;
      endif
      Lu(i) = j ;
   endfor

   for [s key]=u

      if !strcmp(key, "x"), continue, endif

      N = size(s) ; N0 = prod(N(2:end)) ;
      v.(key) = nan(rows(v.id),N0) ;
      v.(key)(Lu,:) = reshape(s, rows(u.id), N0) ;
      v.(key) = reshape(v.(key), [rows(v.id), N(2:end)]) ;

   endfor

endfunction


function res = fixsort (x)

   ## usage:  res = fixdate (x)
   ##
   ## fix sorting of x

   n = length(x) ;
   res = false(n, 1) ;

   j = i = 1 ; res(i) = true ; wx = x(i) ;
   while (++j <= n)
      if (res(j) = (x(j) > wx))
	 wx = x(j) ;
      else
	 if (j == n)
	    error("fill_date: fixsort: reached eof.") ;
	 endif
      endif
   endwhile

endfunction
